package com.wkhyapp.lm.view;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.wkhyapp.lm.adapter.GoodsAdapter;
import com.wkhyapp.lm.adapter.GoodsListAdapter;
import com.wkhyapp.lm.adapter.GoodsXCListAdapter;
import com.wkhyapp.lm.base.SuperActivity;
import com.wkhyapp.lm.contract.XiangCePresenter;
import com.wkhyapp.lm.contract.XiangCeView;
import com.wkhyapp.lm.R;
import com.wkhyapp.lm.http.vo.Goods;
import com.wkhyapp.lm.utils.GlideLoader;
import com.wkhyapp.lm.utils.ImgDonwloads;
import com.wkhyapp.lm.utils.MemberUtils;
import com.wkhyapp.lm.utils.PreferenceUtils;
import com.wkhyapp.lm.utils.StatusBarFontUtil;
import com.wkhyapp.lm.utils.StringUtils;
import com.wkhyapp.lm.weigit.EmptyView;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.functions.Action1;

public class XiangCeActivity extends SuperActivity<XiangCePresenter>  implements XiangCeView{

    @BindView(R.id.refresh_view)
    SwipeRefreshLayout refresh_view;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    private GoodsXCListAdapter goodsXCListAdapter;
    private List<Goods> goodses;
    private int mCurrentPage = 1;
    private View headView;
    private ImageView xcIv;
    @BindView(R.id.back_iv)
    ImageView back_iv;
    @BindView(R.id.plgl_tv)
    TextView  plgl_tv;
    @BindView(R.id.xcyl_tv)
    TextView  xcyl_tv;
    @BindView(R.id.sousuo_rl)
    RelativeLayout sousuo_rl;
    @BindView(R.id.xcfl_rl)
    RelativeLayout xcfl_rl;
    Button zhuaqu_but,clear_but;
    EditText url_et;
    ArrayList<String> pathList = new ArrayList<>();
    View empty_view;
    @BindView(R.id.searc_et)
    EditText searc_et;
    String key;
    @Override
    public void initUI() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            translucentStatusBar();
        }
        StatusBarFontUtil.setLightStatusBarColor(this);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        empty_view = EmptyView.getView(mContext,R.layout.empty_view,R.drawable.wuzhuangtai,"暂无商品");
        goodses = new ArrayList<>();
        headView = View.inflate(mContext, R.layout.head_xiangce, null);
        xcIv = (ImageView)headView.findViewById(R.id.xc_iv);
        url_et = (EditText) headView.findViewById(R.id.url_et);
        zhuaqu_but = (Button) headView.findViewById(R.id.zhuaqu_but);
        clear_but = (Button) headView.findViewById(R.id.clear_but);


        goodsXCListAdapter = new GoodsXCListAdapter(R.layout.item_xc_goods,goodses);
        refresh_view.setColorSchemeColors(Color.parseColor("#FFEC48"),Color.parseColor("#FFEC48"));
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler_view.setLayoutManager(manager);
        goodsXCListAdapter.addHeaderView(headView);
        recycler_view.setAdapter(goodsXCListAdapter);
        refresh_view.setRefreshing(false);
        String url =  PreferenceUtils.getInstance().getPrefString("xc",null);
        if(!StringUtils.isEmpty(url)){
            url_et.setText(url);
        }
        mPresenter.getData(key);

    }

    @Override
    protected void initListener() {
        xcIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击button之后RxPermissions会为我们申请运行时权限
                RxPermissions.getInstance(XiangCeActivity.this)
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)//这里填写所需要的权限多个的话可以逗号隔开
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                                    goTo(UpImageActivity.class);
                                } else {//表示权限被拒绝
                                    Log.i("permissions", Manifest.permission.READ_CALENDAR + "：获取失败"  );
                                }
                            }
                        });
            }
        });


        xcfl_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goTo(UserCategoryActivity.class);
            }
        });

        back_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        zhuaqu_but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("".equals(url_et.getText().toString())){
                    TToast("请输入相册地址");
                    return;
                }
                PreferenceUtils.getInstance().setPrefString("xc",url_et.getText().toString().trim());
                goTo(GrabAlbumActivity.class,url_et.getText().toString().trim());
            }
        });
        goodsXCListAdapter.setLoadMoreView(new LoadMoreView() {
            @Override
            public int getLayoutId() {
                return R.layout.view_index_load_more;
            }

            @Override
            protected int getLoadingViewId() {
                return com.chad.library.R.id.load_more_loading_view;
            }
            @Override
            protected int getLoadFailViewId() {
                return com.chad.library.R.id.load_more_load_fail_view;
            }
            @Override
            protected int getLoadEndViewId() {
                return com.chad.library.R.id.load_more_load_end_view;
            }
        });

        goodsXCListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mCurrentPage = mCurrentPage+1;
                mPresenter.getDataMore(mCurrentPage,key);

            }
        });
        refresh_view.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                 key =  searc_et.getEditableText().toString();
                if(!StringUtils.isEmpty(key)){
                    mPresenter.getData(key.trim());
                }
                mPresenter.getData(key);
            }
        });

        plgl_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goTo(BatchActivity.class);
            }
        });

        xcyl_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goTo(ShopActivity.class, MemberUtils.getUid());
            }
        });

        goodsXCListAdapter.setCallBack(new GoodsXCListAdapter.callBack() {
            @Override
            public void del(Goods item) {
                showLoad("正在删除");
              mPresenter.delete(item.getId());
            }

            @Override
            public void down(Goods item) {
                ImgDonwloads.donwloadImgs(mContext,item.getGoodsImgs());
            }

            @Override
            public void setTop(Goods item) {
               mPresenter.setUp(item.getId());
            }

            @Override
            public void info(Goods item) {
               goTo(EditorGoodsActivity.class,item);
            }

            @Override
            public void share(Goods item) {
                goTo(ShareGoodsActivity.class,item.getId());
            }

        });

        searc_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    key = v.getText().toString();
                    mCurrentPage = 1;
                    if(!StringUtils.isEmpty(key)){
                        mPresenter.getData(key.trim());
                    }

                }
                return false;
            }
        });





//        sousuo_rl.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//               // goTo(SearchActivity.class);
//                ImageConfig imageConfig
//                        = new ImageConfig.Builder(XiangCeActivity.this , new GlideLoader())
//                        // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
//                        .steepToolBarColor(getResources().getColor(R.color.black))
//                        // 标题的背景颜色 （默认黑色）
//                        .titleBgColor(getResources().getColor(R.color.black))
//                        // 提交按钮字体的颜色 （默认白色）
//                        .titleSubmitTextColor(getResources().getColor(R.color.white))
//                        // 标题颜色 （默认白色）
//                        .titleTextColor(getResources().getColor(R.color.white))
//                        // 开启多选 （默认为多选） (单选 为 singleSelect)
//                        .mutiSelect()
//                        // 多选时的最大数量 （默认 9 张）
//                        .mutiSelectMaxSize(9)
//                        // 已选择的图片路径
//                        .pathList(pathList)
//                        // 拍照后存放的图片路径（默认 /temp/picture）
//                        .filePath("/ImageSelector/Pictures")
//                        // 开启拍照功能 （默认关闭）
//                        .build();
//
//
//                ImageSelector.open(imageConfig); // 开启图片选择器
//            }
//        });


        clear_but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.clearXC();
                url_et.setText("");
                PreferenceUtils.getInstance().setPrefString("xc",null);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            // Get Image Path List
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            for (String path : pathList) {
                Log.e("已选择图片的路径为-----", path);
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_xiang_ce;
    }

    @Override
    protected void afterCreate() {

    }

    @Override
    public void setGoods(List<Goods> list) {
        goodses.clear();
        if(list!=null&&list.size()>0){
            goodses.addAll(list);
            goodsXCListAdapter.removeFooterView(empty_view);
        }else{
            goodsXCListAdapter.removeFooterView(empty_view);
            goodsXCListAdapter.addFooterView(empty_view);
        }
        goodsXCListAdapter.notifyDataSetChanged();
        refresh_view.setRefreshing(false);
        goodsXCListAdapter.loadMoreComplete();

    }

    @Override
    public void setGoodsMore(List<Goods> list) {
        if(list.size()==0){
            goodsXCListAdapter.loadMoreComplete();
            goodsXCListAdapter.loadMoreEnd();
        }else{
            goodses.addAll(list);
            goodsXCListAdapter.notifyDataSetChanged();
            goodsXCListAdapter.loadMoreComplete();
        }
    }

    @Override
    public void setSucc(String str) {
        TToast(str);
        mPresenter.getData(key);
    }

    @Override
    protected XiangCePresenter createPresenter() {
        return mPresenter = new XiangCePresenter(this);
    }

    @Override
    public void onResume() {
        mPresenter.getData(key);
        super.onResume();
    }



}
